package com.zhihu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhihu.constants.RedisConstants;
import com.zhihu.mapper.DeepSeekMapper;
import com.zhihu.po.DeepSeek;
import com.zhihu.result.DeepSeekRequest;
import com.zhihu.service.DeepSeekService;
import com.zhihu.vo.DeepSeekVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
@RequiredArgsConstructor
public class DeepSeekServicelmpl extends ServiceImpl<DeepSeekMapper, DeepSeek> implements DeepSeekService {

    private final RestTemplate restTemplate;


    public String generateText(String userPrompt) {
        DeepSeekRequest request = new DeepSeekRequest();
        request.setModel("deepseek-chat");  // 根据文档调整模型名称
        request.setMessages(List.of(
                new DeepSeekRequest.Message("user", userPrompt)
        ));
        request.setTemperature(0.7);

        try {
            DeepSeekVo response = restTemplate.postForObject(RedisConstants.DEEPSEEK_URL, request, DeepSeekVo.class);
            return response.getChoices().get(0).getMessage().getContent();
        } catch (RestClientException e) {
            if (e instanceof HttpStatusCodeException) {
                String responseBody = ((HttpStatusCodeException) e).getResponseBodyAsString();
                int statusCode = ((HttpStatusCodeException) e).getStatusCode().value();
                System.err.println("DeepSeek API 错误: " + statusCode + " - " + responseBody);
            }
            throw new RuntimeException("Failed to call DeepSeek API", e);
        }
    }
}